package com.lz.ccjdemo.utils;

import android.arch.lifecycle.MutableLiveData;
import android.os.Handler;

public class DataChangeUtils {
    //数据定义
    private MutableLiveData<String> strData = new MutableLiveData<>();

    private static DataChangeUtils instance;

    //创建单例 避免重复创建多个实例
    public static DataChangeUtils getInstance() {
        if (instance == null) {
            instance = new DataChangeUtils();
        }
        return instance;
    }

    //数据状态，用于监听数据变化 数据发生变化后会通知所有监听者
    public MutableLiveData<String> getStrData() {
        return strData;
    }

    //设置更新数据 strData.setValue(str)
    public void setStrData(String str) {
        strData.setValue(str);
    }

    //模拟数据更新
    Handler handler = new Handler();
    Runnable run = new Runnable() {
        @Override
        public void run() {
            //模拟数据更新
           setStrData("当前更新数据时间 "+System.currentTimeMillis());
           handler.postDelayed(run,2000);
        }
    };

    //模拟数据更新
    public void testDataUpdate() {
        handler.postDelayed(
                run, 2000);
    }

    //模拟数据更新  关闭数据更新
    public void closeRun(){
        handler.removeCallbacks(run);
        instance=null;
    }
}
